package com.java1234.controller;

import com.java1234.entity.Config;
import com.java1234.entity.R;
import com.java1234.entity.SignRecord;
import com.java1234.service.ConfigService;
import com.java1234.service.SignRecordService;
import com.java1234.util.GeoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 签到记录表 前端控制器
 * </p>
 *
 * @author zhai
 * @since 2025-05-10
 */
@RestController
@RequestMapping("/sys/sign")
public class SignRecordController {

    @Autowired
    private SignRecordService signService;
    @Autowired
    private ConfigService configService;

    @PostMapping
    @PreAuthorize("hasAuthority('system:sign:in')")
    public R signIn(@RequestBody SignRecord dto) {

        // 1. 从数据库或配置中心获取签到点配置
        List<Config> list = configService.list();
        if (list.size() != 3) {
            return R.error("签到管理配置错误");
        }


        // 2. 校验签到范围（示例坐标：公司位置）
        BigDecimal companyLng = new BigDecimal(list.stream().filter(s->s.getId()==1).collect(Collectors.toList()).get(0).getValue());
        BigDecimal companyLat = new BigDecimal(list.stream().filter(s->s.getId()==2).collect(Collectors.toList()).get(0).getValue());
        Integer MAX_DISTANCE = Integer.valueOf(list.stream().filter(s->s.getId()==3).collect(Collectors.toList()).get(0).getValue());
        BigDecimal distance = GeoUtils.calculateDistance(
                dto.getLng(), dto.getLat(),
                companyLng, companyLat
        );
        // 3. 判断是否在500米范围内
        if (distance.intValue() > MAX_DISTANCE) {
            return R.error("超出签到范围");
        }
        // 4. 保存签到记录
        SignRecord record = new SignRecord();
        record.setUserId(dto.getUserId());
        record.setLng(dto.getLng());
        record.setLat(dto.getLat());
        record.setAddress(dto.getAddress());
        record.setDistance(distance);
        record.setSignTime(LocalDateTime.now());

        boolean success = signService.save(record);
        return success ? R.ok("签到成功") : R.error("签到失败");
    }

    @GetMapping("/status")
    @PreAuthorize("hasAuthority('system:sign:status')")
    public R getSignRecordStatus(SignRecord dto) {
        boolean hasSignRecorded = signService.checkTodaySigned(dto.getUserId());
        if (hasSignRecorded) return R.ok("yes");
        return R.ok("no");
    }

}